package org.hncors.gnssparse;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.southgnss.connect.DataLinkerType;
import com.southgnss.connect.DeviceParManage;
import com.southgnss.connect.GnssInfoCallBackLinstner;
import com.southgnss.connect.TopDeviceManage;
import com.southgnss.location.DateUtil;

import org.hncors.gnssparse.activity.BlueSearchConnectActivity;

import java.util.Date;
import java.util.Locale;


public class MainBakActivity extends AppCompatActivity implements View.OnClickListener, GnssInfoCallBackLinstner {

    private LinearLayout layoutTonnectionType;
    private TextView tvGnssInfo;
    private Button btnBluetoothDevice;
    private TextView tvBluetoothDeviceInfo;
    private LinearLayout layoutBluetooth;
    private Button btnConnect;

    private Button btnSetting;
    private Button btnDisConnect;
    private TextView tvConnetionType;
    private String strName;
    private boolean connState = false;

    private String strAddress = "";
    private int connectType = 0;//0-本身，1-蓝牙
    private static final int PERMISSION_LOCATION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_bak);
        initData();
        initUI();
    }

    static Handler mHandler = new Handler();
    Runnable onTimerRunnable = new Runnable() {
        @Override
        public void run() {
            String strInfo = String.format(Locale.ENGLISH, "%s:%.10f%n %s:%.10f%n %s:%.4f%n %s:%.4f%n %s:%.4f%n " +
                            "%s:%.4f%n %s:%.4f%n %s:%.4f%n %s:%.4f%n %s:%.4f%n %s:%s%n %s:%s%n %s:%d%n %s:%d%n " +
                            "%s:%s%n %s:%s%n %s:%s%n %s:%s%n "

                    , getString(R.string.B), TopDeviceManage.getInstance(null).getLatitude()
                    , getString(R.string.L), TopDeviceManage.getInstance(null).getLongitude()
                    , getString(R.string.H), TopDeviceManage.getInstance(null).getAltitude()
                    , getString(R.string.HRMS), TopDeviceManage.getInstance(null).getHrms()
                    , getString(R.string.speed), TopDeviceManage.getInstance(null).getSpeed()
                    , getString(R.string.heading), TopDeviceManage.getInstance(null).getBearing()
                    , getString(R.string.PDOP), TopDeviceManage.getInstance(null).getPdop()
                    , getString(R.string.HDOP), TopDeviceManage.getInstance(null).getHdop()
                    , getString(R.string.VDOP), TopDeviceManage.getInstance(null).getVdop()
                    , getString(R.string.VRMS), TopDeviceManage.getInstance(null).getVrms()
                    , getString(R.string.statusType), getCurSolutionState(TopDeviceManage.getInstance(null).getStatusType())
                    , getString(R.string.time), DateUtil.formatDate(new Date(TopDeviceManage.getInstance(null).getLocalTime()))
                    , getString(R.string.age), TopDeviceManage.getInstance(null).getAge()
                    , getString(R.string.m_tSatNum), TopDeviceManage.getInstance(null).getSatInView()
                    , "固件版本", DeviceParManage.GetInstance().GetRTKAppVer()
                    , "工作模式", DeviceParManage.GetInstance().GetCurSysMode()
                    , "电池剩余", DeviceParManage.GetInstance().getPowerFree().isEmpty() ? "" : (DeviceParManage.GetInstance().getPowerFree() + "%")
                    , "差分站ID", TopDeviceManage.getInstance(null).getChangeStationID()
            );
            tvGnssInfo.setText(strInfo);
            mHandler.postDelayed(onTimerRunnable, 1000);
        }
    };

    private void initData() {
        connectType = ProgramConfigWrapper.GetInstance(this).GetConnectType();
        strName = ProgramConfigWrapper.GetInstance(this).GetBluetoothName();
        strAddress = ProgramConfigWrapper.GetInstance(this).GetBluetoothAddress();
        TopDeviceManage.getInstance(this).setGnssInfoListener(this);

    }

    private void initUI() {
        //连接类型
        layoutTonnectionType = (LinearLayout) findViewById(R.id.layoutConectionTypeSelect);
        if (layoutTonnectionType != null)
            layoutTonnectionType.setOnClickListener(this);
        tvConnetionType = (TextView) findViewById(R.id.tvConnetionType);
        tvConnetionType.setText(connectType == 0 ? getString(R.string.local) : getString(R.string.bluetooth));
        //蓝牙相关
        layoutBluetooth = (LinearLayout) findViewById(R.id.layoutBluetooth);
        btnBluetoothDevice = (Button) findViewById(R.id.bluetoothDevice);
        btnBluetoothDevice.setOnClickListener(this);
        tvBluetoothDeviceInfo = (TextView) findViewById(R.id.bluetoothDeviceInfo);
        tvBluetoothDeviceInfo.setText("设备名字：" + strName + "  设备地址：" + strAddress);
        //gps数据显示
        tvGnssInfo = (TextView) findViewById(R.id.tvGnssInfo);
        //连接
        btnConnect = (Button) findViewById(R.id.btnConnect);
        btnConnect.setOnClickListener(this);
        btnDisConnect = (Button) findViewById(R.id.btnDisConnect);
        btnDisConnect.setOnClickListener(this);
        btnSetting = (Button) findViewById(R.id.btnSetting);
        btnSetting.setOnClickListener(this);

        if (connectType == 0) {
            layoutBluetooth.setVisibility(View.GONE);
            tvConnetionType.setText(getString(R.string.local));
        } else if (connectType == 1) {
            layoutBluetooth.setVisibility(View.VISIBLE);
            tvConnetionType.setText(getString(R.string.bluetooth));
        }
        mHandler.post(onTimerRunnable);
        connect();
    }

    private String getCurSolutionState(int statusType) {
        String statusTypeString = "";
        switch (statusType) {
            case 0:// 无效定位
                break;
            case 1:// 单点
                statusTypeString = "单点";
                break;
            case 2:// 差分
            case 3:
                statusTypeString = "差分";
                break;
            case 4:// 固定
                statusTypeString = "固定";
                break;
            case 8:
                statusTypeString = "固定";
                break;
            case 5:// 浮动
                statusTypeString = "浮动";
                break;
            default:
                break;
        }
        return statusTypeString;
    }

    public void setConnectUI(boolean isConnectSuccess) {
        if (isConnectSuccess) {
            btnConnect.setVisibility(View.GONE);
            btnDisConnect.setVisibility(View.VISIBLE);
            layoutTonnectionType.setEnabled(false);
            tvGnssInfo.setText("");
        } else {
            btnConnect.setVisibility(View.VISIBLE);
            btnDisConnect.setVisibility(View.GONE);
            layoutTonnectionType.setEnabled(true);
            tvGnssInfo.setText("");
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.gnss_menu2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.itemMap:
                onMap();
                break;
            case R.id.itemGnssList:
                onGnssSatelliteList();
                break;
            case R.id.itemGnssMap:
                onGnssSatelliteMap();
                break;
            case R.id.itemDebug:
                onDebug();
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void onGnssSatelliteList() {
        Intent newIntent = new Intent(this, SettingPageGnssInfoSatelliteListActivity.class);
        startActivityForResult(newIntent, 100);
    }

    private void onGnssSatelliteMap() {
        Intent newIntent = new Intent(this, SatellitesViewActivity.class);
        startActivityForResult(newIntent, 100);
    }

    private void onDebug() {
        Intent newIntent = new Intent(this, SettingPageDebugActivity.class);
        startActivity(newIntent);
    }
    private void onMap() {
        Intent newIntent = new Intent(this, MapActivity.class);
        startActivityForResult(newIntent, 100);
    }

    public void deviceInfo(View view) {
        if (connState) {
            Intent intent = new Intent(this, DeviceInfoActivity.class);
            startActivity(intent);
        } else {
            Toast.makeText(this, "连接蓝牙", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bluetoothDevice://选择蓝牙设备
                Intent intent = new Intent(this, BlueSearchConnectActivity.class);
                startActivityForResult(intent, 10);
                break;
            case R.id.layoutConectionTypeSelect://选择连接方式，本身或者蓝牙
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(getString(R.string.main_page_connection_type_tip));
                builder.setSingleChoiceItems(R.array.connectType, connectType, new ConnectTypeSingeChoice());
                AlertDialog dialog = builder.create();
                dialog.show();
                break;
            case R.id.btnConnect:
                requestPermission(Manifest.permission.ACCESS_FINE_LOCATION, PERMISSION_LOCATION);
                break;
            case R.id.btnDisConnect:
                connState = false;
                TopDeviceManage.getInstance(this).disConnect();
                setConnectUI(false);
                break;
            case R.id.btnSetting:
                Intent intent2 = new Intent(this, SettingPageRtkManagerNetConfigBluetooth.class);
                startActivity(intent2);
                break;
            default:
                break;
        }
    }

    private void connect() {
        if (connectType == 0) {
            connectLocal();
        } else if (connectType == 1) {
            connectBluetooth();
        }
    }

    /**
     * 申请权限
     *
     * @param permission
     * @param requestCode
     */
    private void requestPermission(String permission, int requestCode) {
        if (!isGranted(permission)) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
                Toast.makeText(this, "该功能需要位置权限，请打开位置权限！！！", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestCode);
            }
        } else {
            connect();
        }
    }

    private boolean isGranted(String permission) {
        return !isMarshmallow() || isGranted_(permission);
    }

    private boolean isGranted_(String permission) {
        int checkSelfPermission = ActivityCompat.checkSelfPermission(this, permission);
        return checkSelfPermission == PackageManager.PERMISSION_GRANTED;
    }

    private boolean isMarshmallow() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_LOCATION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    connect();
                } else {
                    Toast.makeText(this, "位置权限未打开！！！", Toast.LENGTH_SHORT).show();
                }
                return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    public class ConnectTypeSingeChoice implements DialogInterface.OnClickListener {

        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            connectType = i;
            if (i == 0) {
                layoutBluetooth.setVisibility(View.GONE);
                tvConnetionType.setText(getString(R.string.local));
            } else if (i == 1) {
                layoutBluetooth.setVisibility(View.VISIBLE);
                tvConnetionType.setText(getString(R.string.bluetooth));
            }
            ProgramConfigWrapper.GetInstance(MainBakActivity.this).SetConnectType(connectType);
            dialogInterface.dismiss();
        }
    }

    private void connectBluetooth() {
        if (strAddress.equals("")) {
            Toast.makeText(this, getString(R.string.please_choose_reliable_bluetooth_device), Toast.LENGTH_SHORT).show();
            return;
        }
        TopDeviceManage.getInstance(this).setDataLink(DataLinkerType.BLUETOOTH);
        TopDeviceManage.getInstance(this).connect(strAddress);
    }

    private void connectLocal() {
        if (!TopDeviceManage.getInstance(this).isGpsEnable()) {
            Intent callGPSSettingIntent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            this.startActivity(callGPSSettingIntent);
            Toast.makeText(this, getString(R.string.setting_open_gps), Toast.LENGTH_SHORT).show();
            return;
        }
        TopDeviceManage.getInstance(this).setDataLink(DataLinkerType.LOCAL);
        TopDeviceManage.getInstance(this).connect("");
    }

    @Override
    public void callback(final String strGnssInfo) {
    }

    @Override
    public void connectCallback(final boolean bSuccess) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                connState = bSuccess;
                setConnectUI(bSuccess);
                if (bSuccess) {
                    Toast.makeText(MainBakActivity.this, getString(R.string.connect_success), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(MainBakActivity.this, getString(R.string.connect_fail), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 10 && resultCode == RESULT_OK) {
            strName = data.getStringExtra("BluetoothName");
            strAddress = data.getStringExtra("BluetoothAddress");
            tvBluetoothDeviceInfo.setText(getString(R.string.blue_device_name) + ":" + strName +
                    "  " + getString(R.string.blue_device_address) + ":" + strAddress);
            ProgramConfigWrapper.GetInstance(this).SetBluetoothName(strName);
            ProgramConfigWrapper.GetInstance(this).SetBluetoothAddress(strAddress);
        }
        if (requestCode == 100 && resultCode == RESULT_OK) {
            //            if (data.getBooleanExtra("isClearSateListener", true))
            //                TopDeviceManage.getInstance(this).clearGnssSateInfoListener();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacks(onTimerRunnable);
        }
        ProgramConfigWrapper.GetInstance(this).SetBluetoothName(strName);
        ProgramConfigWrapper.GetInstance(this).SetBluetoothAddress(strAddress);
        TopDeviceManage.getInstance(this).disConnect();
        super.onDestroy();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            //提示是否退出软件
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getResources().getString(R.string.ProgramItemDialogTip));
            builder.setMessage(getResources().getString(R.string.titleExit));
            builder.setPositiveButton(getResources().getString(R.string.ProgramItemDialogTipSure), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {

                    System.exit(0);
                }
            });
            builder.setNegativeButton(getResources().getString(R.string.ProgramItemDialogTipCancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                }
            });
            builder.show();
        }

        return super.onKeyDown(keyCode, event);
    }
}
